package com.bieber.server.serialize;

import com.bieber.common.Constants;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Registration;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;

import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by bieber on 2015/8/20.
 */
public class KryoSerializer implements Serializer {

    private static final Kryo KRYO = new Kryo();

    private static final ConcurrentHashMap<Class<?>,Registration> REGISTRATION_MAP = new ConcurrentHashMap<Class<?>, Registration>();

    @Override
    public byte[] serialize(Object object) {
        if(!REGISTRATION_MAP.containsKey(object.getClass())){
            REGISTRATION_MAP.putIfAbsent(object.getClass(),KRYO.register(object.getClass()));
        }
        Output output  = new Output(Constants.SERIALIZE_BUFFER_SIZE,Constants.SERIALIZE_MAX_BUFFER_SIZE);
        KRYO.writeObject(output,object);
        output.flush();
        return output.toBytes();
    }

    @Override
    public<T extends Object> T deSerialize(byte[] bytes,Class<T> type) {
        Input input = new Input(bytes);
        return  KRYO.readObject(input,type);
    }
}
